//
// Created by test on 22-11-26.
//
//
// Created by test on 22-11-26.
//
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<stdio.h>
int main(int argc,char* argv[]){
    if(argc<=2){
        printf("error");
    }
    const char* ip=argv[1];
    int port=atoi(argv[2]);
    struct sockaddr_in serv_addr;
    bzero(&serv_addr,sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(port);
    inet_pton(AF_INET,ip,&serv_addr.sin_addr);
    int listenfd=socket(PF_INET,SOCK_STREAM,0);
    assert(listenfd>=0);
    int ret=bind(listenfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
    assert(ret!=-1);
    ret=listen(listenfd,5);
    assert(ret!=-1);
    struct sockaddr_in client_addr;
    socklen_t client_addrlen=sizeof(client_addr);
    int connfd=accept(listenfd,(struct sockaddr*)&client_addr,&client_addrlen);
    if(connfd<0){
        printf("error");
    }
    char buf[1024];
    fd_set read_fds;
    fd_set exception_fds;
    FD_ZERO(&read_fds);
    FD_ZERO(&exception_fds);
    while(1){
        memset(buf,'\0',sizeof(buf));
        FD_SET(connfd,&read_fds);
        FD_SET(connfd,&exception_fds);
        ret=select(connfd+1,&read_fds,NULL,&exception_fds,NULL);
        if(ret<0){
            printf("errro");
            break;
        }
        if(FD_ISSET(connfd,&read_fds)){
            ret=recv(connfd,buf,sizeof(buf)-1,0);
            if(ret<=0){
                connfd=accept(listenfd,(struct sockaddr*)&client_addr,&client_addrlen);
                continue;
            }
            printf("get %d bytes of normal data:%s\n",ret,buf);
        }
        else if(FD_ISSET(connfd,&exception_fds)){
            ret=recv(connfd,buf,sizeof(buf)-1,MSG_OOB);
            if(ret<=0){
                connfd=accept(listenfd,(struct sockaddr*)&client_addr,&client_addrlen);
                continue;
            }
            printf("get %d bytes of oob data:%s\n",ret,buf);
        }
    }
    close(connfd);
    close(listenfd);
    return 0;
}